<?php
/**
* Some utility functions.
*
* Copyright (c) 2009 James Gauld <james@jamesgauld.net>
* This file is part of Scribble.
* @license http://www.scribblecms.co.uk/license.txt
*
* @package Scribble
*/

/**
* Generates a unique identifier for use in a db record's PK column.
*
* To store this value, the PK must have the type:
*		CHAR(32) NOT NULL DEFAULT ''
*
* The returned identifier does not include the hyphens that are used in the
* standard uuid format (8-4-4-4-12).
*
* This code was adpated from examples provided at
* @link http://php.net/manual/en/function.uniqid.php
*
* References:
* http://www.codinghorror.com/blog/archives/000817.html
* http://krow.livejournal.com/497839.html
* http://www.mysqlperformanceblog.com/2007/03/13/to-uuid-or-not-to-uuid/
* http://kekoav.com/blog/36-computers/58-uuids-as-primary-keys-in-mysql.html
*
* @return string 32-char string
*/
function scribble_guid() {
	$pr_bits = "";
	for($cnt=0; $cnt<16; $cnt++) {
		$pr_bits .= chr(mt_rand(0, 255));
	}
	$time_low = bin2hex(substr($pr_bits, 0, 4));
	$time_mid = bin2hex(substr($pr_bits, 4, 2));
	$time_hi_and_version = bin2hex(substr($pr_bits, 6, 2));
	$clock_seq_hi_and_reserved = bin2hex(substr($pr_bits, 8, 2));
	$node = bin2hex(substr($pr_bits, 10, 6));

	$time_hi_and_version = hexdec($time_hi_and_version);
	$time_hi_and_version = $time_hi_and_version >> 4;
	$time_hi_and_version = $time_hi_and_version | 0x4000;

	$clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
	$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
	$clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

	return sprintf('%08s%04s%04x%04x%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
}

/**
* Returns a filesize with appropriate unit suffix.
*
* @param int Bytes
* @return string
*/
function scribble_formatFilesize($bytes) {
	if($bytes<1024) {
		$suffix = " bytes";
	}
	else if(($bytes /= 1024)<1024) {
		$suffix = " KB";
	}
	else if(($bytes /= 1024)<1024) {
		$suffix = " MB";
	}
	else if(($bytes /= 1024)<1024) {
		$suffix = " GB";
	}
	else {
		$suffix = " TB";
	}
	return number_format($bytes, 2).$suffix;
}

/**
* Returns a friendlier version of a timestamp in the formats:
*		6 seconds ago
*		12 minutes ago
*		5 hours ago
*		3 days ago
*		5th Jan 2009
*
* @param int Unix timestamp
* @return string
*/
function scribble_timeAgo($t) {
	$diff = time()-$t;
	if($diff<60) {
		return "{$diff} seconds ago";
	}
	else if($diff<120) {
		return "1 minute ago";
	}
	else if($diff<3600) {
		return floor($diff/60)." minutes ago";
	}
	else if($diff<7200) {
		return "1 hour ago";
	}
	else if($diff<86400) {
		return floor($diff/3600)." hours ago";
	}
	else if($diff<172800) {
		return "1 day ago";
	}
	else if($diff<2592000) {
		return floor($diff/86400)." days ago";
	}
	else {
		return date("jS F Y", $t);
	}
}
?>